<template>
  <a-card style="width:100%">
    <a-spin :spinning="spinning">
      <a-form :form="form" layout="Vertical">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item
              label="培养模式"

            >
              <a-select v-decorator="['pymsm',
                {
                  rules: [{ required: true, message: '请选择培养模式!' }],
                }]" labelInValue @change="e => handleChange(e, 'pyms')" :disabled="completeBaseForm">
                <a-select-option v-for="i in TYPE0347" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
  <!--        <a-col :md="12" :sm="24" v-if="pymsm === '01'">
            <a-form-item
              label="门类"
              :labelCol="{span: 9,offset: 1}"
              :wrapperCol="{span: 13, offset: 1}"
            >
              <a-select showSearch :filterOption="filterOption" v-decorator="['xkmlm',
                {
                  rules: [{ required: true, message: '请选择门类!' }],
                }]" @change="e => handleXkmlChange(e, 'xkml')" labelInValue :disabled="completeBaseForm">
                <a-select-option v-for="i in selectMenu.subjectList" :key="i.id" :value="i.xkdm">{{ i.xkdm + ' ' + i.xkmc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>-->
          <a-col :md="8" :sm="24" v-if="pymsm === '01'||pymsm === '03'">
            <a-form-item
              label="一级学科"

            >
              <a-select showSearch :filterOption="filterOption" v-decorator="['xkzym',
                {
                  rules: [{ required: true, message: '请选择一级学科!' }],
                }]" @change="e => handleChange(e, 'xkzym')" labelInValue :disabled="completeBaseForm">
                <a-select-option v-for="i in selectMenu.subjectList" :key="i.id" :value="i.xkdm">{{ i.xkdm + ' ' +
                  i.xkmc }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24" v-if="pymsm === '02'">
            <a-form-item
              label="专业领域（类别）"

            >
              <a-select showSearch :filterOption="filterOption" v-decorator="['xkzym',
                {
                  rules: [{ required: true, message: '请选择专业领域（类别）!' }],
                }]" @change="e => handleChange(e, 'xkzym')" labelInValue :disabled="completeBaseForm">
                <a-select-option v-for="i in selectMenu.subjectList" :key="i.id" :value="i.xkdm">{{ i.xkdm + ' ' + i.xkmc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item
              label="培养类别"

            >
              <a-select v-decorator="['xslbm',
                {
                  rules: [{ required: true, message: '请选择培养类别!' }],
                }]" labelInValue @change="e => handleChange(e)" :disabled="completeBaseForm">
                <a-select-option v-for="i in TYPE0075" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- <a-col :md="12" :sm="24">
            <a-form-item
              label="培养来源"
              :labelCol="{span: 9,offset: 1}"
              :wrapperCol="{span: 13, offset: 1}"
            >
              <a-select v-decorator="['xslxm',
                {
                  rules: [{ required: true, message: '请选择培养来源!' }],
                }]" labelInValue @change="e => handleChange(e)" :disabled="completeBaseForm">
                <a-select-option v-for="i in TYPE0503" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col> -->


  <!--        <a-col :md="8" :sm="12">
            <a-form-item label="培养单位"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}">
              <a-select v-decorator="['ssyxm',
                {
                  rules: [{ required: true, message: '请选择培养单位!' }],
                }]" @change="e => handleChange(e, 'yx')" showSearch :filterOption="filterOption" labelInValue :disabled="completeBaseForm">
                <a-select-option v-for="i in selectMenu.yxList" :key="i.id" :value="i.dwh">{{ i.dwh }} {{ i.dwmc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item label="专业"
              :labelCol="{span: 7,offset: 1}"
              :wrapperCol="{span: 15, offset: 1}">
              <a-select v-decorator="['sszydm',
                {
                  rules: [{ required: true, message: '请选择专业!' }],
                }]" @change="e => handleChange(e)" showSearch :filterOption="filterOption" labelInValue :disabled="completeBaseForm">
                &lt;!&ndash; <a-spin slot="notFoundContent" size="small"/> &ndash;&gt;
                <a-select-option v-for="(i,index) in selectMenu.zyList" :key="index" :value="i.zyh">{{ i.zyh }}{{ i.zymc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>-->


          <a-col :md="16" :sm="24">
            <a-form-item
              label="培养方案名称"

            >
              <a-input v-decorator="['pyfamc',
                {
                  rules: [{ required: true, message: '请填写培养方案名称!' }],
                }]"/>
              <a-input  v-decorator="['ssnj']" type="hidden"/>
            </a-form-item>
          </a-col>
          <a-col :md="24" :sm="24" >
            <a-button type="primary" v-if="!completeBaseForm" @click="completeBase" style="margin:0 10px 10px">制定</a-button>
          </a-col>
        </a-row>
        <div style="color: #E51C23" v-if="!completeBaseForm">温馨提示，请尽量按照规则：年级（如：2014级） + 学科/领域名称 + 培养类别名称 + 一级学科/专业学位类别（领域） + “培养方案”，进行培养方案命名。</div>


      </a-form>
      <a-tabs defaultActiveKey="1" v-if="completeBaseForm">
        <a-tab-pane tab="培养方案" key="1">
          <base-form ref="base" :TYPE0301="TYPE0301"/>
        </a-tab-pane>
        <a-tab-pane tab="课程设置" key="2" forceRender>
          <course-set ref="course" :yxList="selectMenu.yxList"/>
        </a-tab-pane>
        <a-tab-pane tab="培养过程" key="3" forceRender>
          <process-set ref="process" :yxList="selectMenu.yxList"/>
        </a-tab-pane>
        <a-tab-pane tab="攻读学位学分要求" key="4" forceRender>
          <credit :temp.sync="temp" :pymsmc.sync="pymsmc" ref="credit"/>
        </a-tab-pane>
      </a-tabs>

      <div class="ant-pro-footer-toolbar" v-if="completeBaseForm">
        <div style="float: right;">
          <a-button @click="back">返回列表</a-button>
          <a-button @click="submit" :loading="loadingBtn" type="primary">提交保存</a-button>
        </div>
      </div>
    </a-spin>
  </a-card>
</template>

<script>
import { mapState } from 'vuex'
import courseSet from './components/courseSet'
import processSet from './components/processSet'
import credit from './components/credit'
import baseForm from './components/base'

export default {
  data () {
    return {
      selectMenu: {
        subjectList: [],
        subSubjectList: [],
      },
      form: this.$form.createForm(this),
      pymsmc: '学术学位',
      pymsm:'01',
      xkmc: '',
      pyfamc: '',
      temp: {},
      completeBaseForm: false,
      loadingBtn: false,
      spinning: false
    }
  },
  components: {baseForm, courseSet, credit, processSet},
  computed: {
    ...mapState({
      systemInfo: state => state.app.systemInfo,
      TYPE0347: state => state.app['TYPE0347'],
      TYPE0075: state => state.app['TYPE0075'],
      TYPE0503: state => state.app['TYPE0503'],
      TYPE0301: state => state.app['TYPE0301']
    })
    // pyfamc () {
    //   return this.form.getFieldValue('dsbh')
    // }
  },
  watch: {
    '$route.query.id': {
      handler (val) {
        this.initPage()
      },
      immediate: true
    }
  },
  created () {
    this.$store.dispatch('app/sysInfo')
    this.$store.dispatch('app/setDictionary', 'TYPE0347')
    this.$store.dispatch('app/setDictionary', 'TYPE0075')
    this.$store.dispatch('app/setDictionary', 'TYPE0301')
    this.$store.dispatch('app/setDictionary', 'TYPE0503')
    this.initSelectMenu()
  },
  methods: {
    initPage () {
      if (this.$route.query.id) {
        this.spinning = true
        this.$api.cultivate.schemeDetail(this.$route.query.id).then(res => {
          this.completeBaseForm = true
          let sche = res.data
          this.temp = sche.pyfamb
          // this.pymsmc = sche.pyfa.pymsmc
          // this.handleChange({label: '', key: sche.pyfa.ssyxm}, 'yx')
          this.handleXkmlChange({key: sche.pyfa.xkmlm});
          this.handleChange({label: sche.pyfa.pymsmc, key: sche.pyfa.pymsm}, 'pyms')
          this.$nextTick(() => {
            // console.log(this.form.getFieldDecorator())
            this.form.setFieldsValue({
              // ssyxm: {key: sche.pyfa.ssyxm},
              // sszydm: {key: sche.pyfa.sszydm},
              pymsm: {key: sche.pyfa.pymsm},
              xkzym: {key: sche.pyfa.xkzym},
              xslbm: {key: sche.pyfa.xslbm},
              // xslxm: {key: sche.pyfa.xslxm},
              xkmlm: {key: sche.pyfa.xkmlm},
              pyfamc: sche.pyfa.pyfamc,
              ssnj: sche.pyfa.ssnj
            })
            this.$refs.base.form.setFieldsValue({
              pymb: sche.pyfa.pymb,
              xynx: sche.pyfa.xynx,
              xynxsm: sche.pyfa.xynxsm,
              yjfx: sche.pyfa.yjfx,
              xwlwsm: sche.pyfa.xwlwsm,
              pyfsyff: sche.pyfa.pyfsyff,
              xkjj:sche.pyfa.xkjj
            })
            this.$refs.course.kcList = sche.pyfakcList.map(kc => {
              return Object.assign({}, kc, {
                kch: kc.kcdm,
                zxs: kc.xs
              })
            })
            this.$refs.process.kcList = sche.pyfaPkcList.map(k => {
              return Object.assign(k, {
                kch: k.kcdm,
                zxs: k.xs
              })
            })
            let creditKeys = Object.keys(this.$refs.credit.form.getFieldsValue())
            creditKeys.forEach(key => {
              let obj = {}
              obj[key] = sche.pyfa[key]
              this.$refs.credit.form.setFieldsValue(obj)
            })
          })
        }).finally(() => {
          this.spinning = false
        })
      } else {
        // this.$api.base.subjectAllByYx({xklb: '01'}).then(res => {
        //   this.$set(this.selectMenu, 'subjectList', res.data)
        // })
        this.$nextTick(() => {
          this.form.setFieldsValue({
            pymsm: {key: '01'},
          })
          this.$api.base.subjectAllByYx({xklb: '02'}).then(res => {
            this.$set(this.selectMenu, 'subjectList', res.data)
          })
        })
      }
    },
    initSelectMenu () {
      let allRequest = [
        this.$api.base.collegeAll()
      ]
      Promise.all(allRequest).then(res => {
        this.$set(this.selectMenu, 'yxList', res[0].data)
      })
    },
    handleXkmlChange(v, k){
      this.form.setFieldsValue({xkzym: ''})
      if (v.key) {
        this.$api.base.subjectAllByYx({fjxkdm: v.key, xklb: ('02')}).then(res => {
          this.$set(this.selectMenu, 'subSubjectList', res.data)
        })
      } else {
        this.selectMenu.subSubjectList = []
      }
    },
    handleChange (v, k) {
      if (k === 'yx') {
        this.form.setFieldsValue({sszydm: ''})
        this.$api.base.majorAll({lsdwh: v.key}).then(res => {
          this.$set(this.selectMenu, 'zyList', res.data)
        })
      }
      if (k === 'pyms') {
        this.pymsm = v.key
        this.pymsmc = v.label
        this.xkmc = ''
        this.form.setFieldsValue({xkzym: ''})
        this.$api.base.subjectAllByYx({xklb: (v.key === '01' || v.key === '03' ? '02' : '04')}).then(res => {
          this.$set(this.selectMenu, 'subjectList', res.data)
        })
      }
      if(k === 'xkzym'){
        this.xkmc = v.label
      }
      this.$nextTick(() => {
        // const pymsm = this.form.getFieldValue('pymsm')
        this.form.setFieldsValue({pyfamc: `${this.systemInfo.currentGrade} ${this.xkmc ? this.xkmc : ''} ${this.form.getFieldValue('xslbm') ? this.form.getFieldValue('xslbm').label : ''} ${this.pymsm ? (this.pymsm === '03' ? '直博生' : (this.pymsm === '01' ? '一级学科' : '专业学位类别（领域）')) : ''} 培养方案`})
      })
    },
    filterOption (value, yx) {
      return yx.componentOptions.children[0].text.indexOf(value) !== -1
    },
    completeBase () {
      this.form.validateFields((err, values) => {
        if (err) {
          return
        }
        let params = {
          pyms: values.pymsm.key,
          xslb: values.xslbm.key,
          // xslx: values.xslxm.key,
          xkdm: values.xkzym.key,
          // yx: values.ssyxm.key,
          // zy: values.sszydm.key
        }
        this.$api.cultivate.getTemplate(params).then(res => {
          let temData = res.data
          this.completeBaseForm = true
          this.temp = res.data.pyfamb
          this.$nextTick(() => {
            this.$refs.course.kcList = temData.pyfambkcList.map(k => {
              return Object.assign(k, {
                kch: k.kcdm,
                zxs: k.xs,
                sfmbkc: 1
              })
            })
            this.$refs.process.kcList = temData.pyfambPkcList.map(k => {
              return Object.assign(k, {
                kch: k.kcdm,
                zxs: k.xs,
                sfmbkc: 1
              })
            })
            this.$refs.credit.form.setFieldsValue(temData.pyfamb)
          })
        })
      })
    },
    back() {
      this.completeBaseForm = false;

    },
    async submit() {
      try {
        const addForm = new Promise((resolve, reject) => {
          this.form.validateFields((err, values) => {
            if (err) {
              reject(new Error('请输入培养方案名称'))
              return
            }
            resolve(values)
          })
        })
        let add = await addForm
        const baseForm = new Promise((resolve, reject) => {
          this.$refs.base.form.validateFields((err, values) => {
            if (err) {
              reject(new Error('请完善培养方案'))
              return
            }
            resolve(values)
          })
        })
        let base = await baseForm
        let kcList = this.$refs.course.kcList.map(k => {
          return Object.assign({}, k, {
            sfmbkc: +k.sfmbkc ? 1 : 0
          })
        })
        let pkcList = this.$refs.process.kcList.map(k => {
          return Object.assign({}, k, {
            sfmbkc: +k.sfmbkc ? 1 : 0
          })
        })
        // if (!kcList.length) {
        //   throw Error('请添加培养方案课程')
        // }
        const creditForm = new Promise((resolve, reject) => {
          this.$refs.credit.form.validateFields((err, values) => {
            if (err) {
              reject(new Error('请完善攻读学位学分要求'))
              return
            }
            resolve(values)
          })
        })
        let pyfa = await creditForm
/*        let credit = this.$refs.credit
        let bxkxf = credit.form.getFieldValue('bxkxf') ? this.form.getFieldValue('bxkxf') : 0
        let xxkxf = credit.form.getFieldValue('xxkxf') ? this.form.getFieldValue('xxkxf') : 0
        let xwkxf = credit.form.getFieldValue('xwkxf') ? this.form.getFieldValue('xwkxf') : 0
        let kczgxf = credit.form.getFieldValue('kczgxf')
        let kczxf = credit.form.getFieldValue('kczxf')
        let total = bxkxf + xxkxf + xwkxf
        if(total > kczgxf || total < kczxf){
          throw Error('课程学分设置只能在最低学分和最高学分之间')
        }*/
        if (pyfa.bxkxf + pyfa.xxkxf >= pyfa.kczgxf) {
          throw Error('攻读学位学分要求：必修课学分和选修课学分加起来必须小于课程最高学分')
        }
        if (pyfa.bxkxf < pyfa.xwkxf) {
          throw Error('攻读学位学分要求：必修课学分必须大于等于学位课学分')
        }
        if (pyfa.bxkms < pyfa.xwkms) {
          throw Error('攻读学位学分要求：必修课门数必须大于等于学位课门数')
        }
        for (const key in add) {
          if (typeof add[key] === 'object') {
            add[key] = add[key].key
          }
        }
        let params = {
          pyfa: Object.assign({}, base, pyfa, add),
          pyfakcList: kcList.map(k => {
            return Object.assign({}, k, {
              kcdm: k.kch,
              xs: k.zxs
            })
          }),
          pyfaPkcList: pkcList.map(k => {
            return Object.assign({}, k, {
              kcdm: k.kch,
              xs: k.zxs
            })
          })
        }
        this.loadingBtn = true
        let apiFn = this.$route.query.id ? 'schemeUpdate' : 'schemeAdd'
        params.pyfa.id = this.$route.query.id
        this.$api.cultivate[apiFn](params).then(res => {
          this.$message.success(res.msg || '制定成功')
          this.completeBaseForm = false
          if (this.$route.query.id) {
            this.$router.back()
          }
        }).finally(() => {
          this.loadingBtn = false
        })
      } catch (error) {
        error.message && this.$message.error(error.message)
      }
    }
  }
}
</script>

<style>

</style>
